package com.utils;

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Email发送邮件工具类
 *
 * @author 闫超
 */
public class SendEmailUtil {


    public static final String HOST = "smtp.aliyun.com";
    public static final String PROTOCOL = "smtp";
    public static final String FROM = "jihuo_myjob@aliyun.com";//发件人的email
    public static final String PWD = "Loveme100";//阿里邮箱的客户端授权密码


    /**
     * 获取Session
     *
     * @return
     */
    private static Session getSession() {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);//设置服务器地址
        props.put("mail.store.protocol", PROTOCOL);//设置协议
        props.put("mail.smtp.auth", true);
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");

        Authenticator authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, PWD);
            }

        };
        Session session = Session.getDefaultInstance(props, authenticator);

        return session;
    }

    public static void send(String toEmail, String code, String email) {

        Session session = getSession();
        try {
            // Instantiate a message
            Message msg = new MimeMessage(session);

            //Set message attributes
            msg.setFrom(new InternetAddress(FROM));
            InternetAddress[] address = {new InternetAddress(toEmail)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject("MyJob激活邮件");
            msg.setSentDate(new Date());
            msg.setContent("<h1>激活账号，点击此链接激活</h1><h3><a href='http://39.108.164.184/checkEmail?email=" + email + "&code=" + code + "'>http://39.108.164.184/checkEmail?email=" + email + "&code=" + code + "</a></h3>", "text/html;charset=UTF-8");


            //Send the message
            Transport.send(msg);
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

}